import { observable, action, computed } from 'mobx'
import Global from 'cvm/common/global'
import Toast from 'components/toast'

export default class commonVM {
  constructor () {
    this.userInfo = Global.userInfo()
  }

  // 用户个人信息
  @observable userInfo = {
    isBlank: 0,
    userId: null,
    blankTime: ''
  }

  // 登录用户Id
  @computed get userId () {
    if (!this.userInfo.userId) {
      return Global.userInfo().userId
    } else {
      return Global.userInfo().userId
    }
  }

  // 分页数据
  @observable pageInfo = {
    status: 'loading',
    page: 1,
    size: 10,
    timeStamp: 0
  }

  @action saveUserInfo = userInfo => {
    this.userInfo = Global.saveUserInfo(userInfo)
  }

  // 处理分页请求
  @action fetchPage = () => {
    let time = this.pageInfo.page === 1 ? Date.parse(new Date()) : this.pageInfo.timeStamp
    this.pageInfo = {
      status: 'loading',
      page: this.pageInfo.page,
      size: this.pageInfo.size,
      timeStamp: time
    }
    if (this.pageInfo.page === 1) {
      Toast.loading(1)
    }
  }

  // 处理分页请求
  @action receivePage = data => {
    if (this.pageInfo.page === 1) {
      Toast.loading(2)
    }
    let status = 'noMore'
    let page = this.pageInfo.page
    if (data) {
      if (data.length >= this.pageInfo.size) {
        page += 1
        status = 'loaded'
      }
    } else {
      status = 'loaded'
    }
    this.pageInfo = {
      status: status,
      page: page,
      size: this.pageInfo.size,
      timeStamp: this.pageInfo.timeStamp
    }
  }
}
